<?php

/**
 *    合作伙伴控制器
 *
 *    @author    Garbin
 *    @usage    none
 */
class OrderApp extends BackendApp
{
    /**
     *    管理
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function index()
    {

        $search_options = array(
            'seller_name'   => Lang::get('store_name'),
            'buyer_name'   => Lang::get('buyer_name'),
            'payment_name'   => Lang::get('payment_name'),
            'order_sn'   => Lang::get('order_sn'),
        );
        /* 默认搜索的字段是店铺名 */
        $field = 'seller_name';
        array_key_exists($_GET['field'], $search_options) && $field = $_GET['field'];
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => $field,       //按用户名,店铺名,支付方式名称进行搜索
                'equal' => 'LIKE',
                'name'  => 'search_name',
            ),array(
                'field' => 'status',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'type',
                'equal' => '=',
                'type'  => 'string',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            ),array(
                'field' => 'order_amount',
                'name'  => 'order_amount_from',
                'equal' => '>=',
                'type'  => 'numeric',
            ),array(
                'field' => 'order_amount',
                'name'  => 'order_amount_to',
                'equal' => '<=',
                'type'  => 'numeric',
            ),
        ));

        //搜索地址信息
        if($_GET['address']){
            $orderextmModel = &m('orderextm');
            $orderextmInfo = $orderextmModel->find(array('conditions'=>"address like '%".$_GET['address']."%' OR region_name like '%".$_GET['address']."%'"));
            if(!empty($orderextmInfo)){
                $orderextmInfo = array_values($orderextmInfo);
                $address_id = '';
                foreach($orderextmInfo as $k=>$v){
                    if($k == 0){
                        $address_id = $v['order_id'];
                    }else{
                        $address_id .= ','.$v['order_id'];
                    }
                }
                $conditions .= ' AND order_alias.order_id IN ('.$address_id.')';
            }
            $this->assign('address',$_GET['address']);
        }

        $model_order =& m('order');
        $page   =   $this->_get_page(10);    //获取分页信息
        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
             $sort  = 'add_time';
             $order = 'desc';
            }
        }
        else
        {
            $sort  = 'add_time';
            $order = 'desc';
        }
        $orders = $model_order->find(array(
            'join'          => 'has_ordergoods,belongs_to_user',
            'fields'         => 'order.*,ordergoods.goods_image,ordergoods.spec_id,ordergoods.goods_name,ordergoods.sales,member.s_name',
            'conditions'    => '1=1 ' . $conditions,
            'limit'         => $page['limit'],  //获取当前页的数据
            'order'         => "$sort $order",
            'count'         => true             //允许统计
        )); //找出所有商城的合作伙伴

        $page['item_count'] = $model_order->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->assign('order_status_list', array(
            ORDER_PENDING => Lang::get('order_pending'),
            ORDER_SUBMITTED => Lang::get('order_submitted'),
            ORDER_ACCEPTED => Lang::get('order_accepted'),
            ORDER_SHIPPED => Lang::get('order_shipped'),
            ORDER_FINISHED => Lang::get('order_finished'),
            ORDER_CANCELED => Lang::get('order_canceled'),
            ORDER_REFUND_SUCCESS => '退款成功',
        ));
        $this->assign('order_type', array(
            GENERAL_ORDER => Lang::get('material'),
            WISH_ORDER => Lang::get('wishOrder'),
        ));
        $this->assign('search_options', $search_options);
        $this->assign('page_info', $page);          //将分页信息传递给视图，用于形成分页条
        $specModel = &m('goodsspec');
        $storeModel = &m('store');

        $storeInfo = '';
        $order_type =& ot('normal');
        $member = &m('member');
        foreach($orders as $k=>&$v){
            if($v['spec_id']){
                $v['specInfo'] = $specModel->get(array('conditions'=>'spec_id = '.$v['spec_id']));
            }
            $v['order_detail'] = $order_type->get_order_detail($v['order_id'], $v);
            $v['memberInfo'] = $member->get(array("conditions"=>"user_id = ".$v['buyer_id']));
            if($v['memberInfo']['second_class']){
                $storeInfo = $storeModel->get(array("conditions"=>"store_id = ".$v['memberInfo']['second_class']));
            }else{
                if($v['memberInfo']['first_class']){
                    $storeInfo = $storeModel->get(array("conditions"=>"store_id = ".$v['memberInfo']['first_class']));
                }
            }
            if(isset($storeInfo['store_name'])){
                $v['s_name'] = $storeInfo['store_name'];
            }
            $v['goods_image'] = WEB_PHOTO_SRC.'/'.$v['goods_image'];
        }
        $this->assign('orders', $orders);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('order.index.html');
    }
    
/**
     * 订单导出
     */
    function export()
    {
        $search_options = array(
            'seller_name'   => Lang::get('store_name'),
            'buyer_name'   => Lang::get('buyer_name'),
            'payment_name'   => Lang::get('payment_name'),
            'order_sn'   => Lang::get('order_sn'),
        );
        /* 默认搜索的字段是店铺名 */
        $field = 'seller_name';
        array_key_exists($_GET['field'], $search_options) && $field = $_GET['field'];
        $conditions = $this->_get_query_conditions(array(array(
                'field' => $field,       //按用户名,店铺名,支付方式名称进行搜索
                'equal' => 'LIKE',
                'name'  => 'search_name',
            ),array(
                'field' => 'status',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            ),array(
                'field' => 'order_amount',
                'name'  => 'order_amount_from',
                'equal' => '>=',
                'type'  => 'numeric',
            ),array(
                'field' => 'order_amount',
                'name'  => 'order_amount_to',
                'equal' => '<=',
                'type'  => 'numeric',
            ),
        ));
        
        $model_order =& m('order');
        $page   =   $this->_get_page(10);    //获取分页信息
        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
             $sort  = 'add_time';
             $order = 'desc';
            }
        }
        else
        {
            $sort  = 'add_time';
            $order = 'desc';
        }
        $orders = $model_order->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'order'         => "$sort $order",
            'join'=>'has_orderextm',
        )); //找出所有商城的合作伙伴

        
        
        import('excelwriter.lib');
        $excel = new ExcelWriter('utf8', 'toexcel');
        if (!$orders) {
            $this->show_warning('no_data');
            return;
        }

        $cols = array();
        $cols_item = array();
        $cols_item[] = '订单编号';
        $cols_item[] = '店铺名称';
        $cols_item[] = '消费者名称';
        $cols_item[] = '消费者邮箱';
        $cols_item[] = '订单状态';
        $cols_item[] = '下单时间';
        $cols_item[] = '支付方式';
        $cols_item[] = '付款时间';
        $cols_item[] = '发货时间';
        $cols_item[] = '快递单号';
        $cols_item[] = '完成时间';
        $cols_item[] = '商品总价';
        $cols_item[] = '折扣';
        $cols_item[] = '订单总价';
        $cols_item[] = '付款留言';
        $cols_item[] = '收货地区';
        $cols_item[] = '收货地址';
        $cols_item[] = '邮编';
        $cols_item[] = '手机';
        $cols_item[] = '快递方式';
        $cols_item[] = '快递费用';

        $cols[] = $cols_item;

        if (is_array($orders) && count($orders) > 0) {
            foreach ($orders as $k => $v) {

                $tmp_col = array();
                $tmp_col[] = $v['order_sn'];
                $tmp_col[] = $v['seller_name'];
                $tmp_col[] = $v['buyer_name'];
                $tmp_col[] = $v['buyer_email'];
                $tmp_col[] = $this->get_status($v['status']);
                $tmp_col[] = local_date('Y-m-d H:i:s', $v['add_time']);
                $tmp_col[] = $v['payment_name'];
                $tmp_col[] = $v['pay_time']?local_date('Y-m-d H:i:s', $v['pay_time']):'';
                $tmp_col[] = $v['ship_time']?local_date('Y-m-d H:i:s', $v['ship_time']):'';
                $tmp_col[] = $v['invoice_no'];
                $tmp_col[] = local_date('Y-m-d H:i:s', $v['finished_time']);
                $tmp_col[] = $v['goods_amount'];
                $tmp_col[] = $v['discount'];
                $tmp_col[] = $v['order_amount'];
                $tmp_col[] = $v['postscript'];
                $tmp_col[] = $v['region_name'];
                $tmp_col[] = $v['address'];
                $tmp_col[] = $v['zipcode'];
                $tmp_col[] = $v['phone_mob'];
                $tmp_col[] = $v['shipping_name'];
                $tmp_col[] = $v['shipping_fee'];
                $cols[] = $tmp_col;
            }
        }
        $excel->add_array($cols);
        $excel->output();
        
    }
    
    function get_status($status) {
        switch ($status) {
            case 0:
                $msg = '已取消';
                break;
            case 10:
                $msg = '发货中';
                break;
            case 11:
                $msg = '待付款';
                break;
            case 20:
                $msg = '待发货';
                break;
            case 30:
                $msg = '已发货';
                break;
            case 40:
                $msg = '交易成功';
                break;
            default:
                break;
        }
        return $msg;
    }

    /**
     *    查看
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function view()
    {
        $order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if (!$order_id)
        {
            $this->show_warning('no_such_order');

            return;
        }

        /* 获取订单信息 */
        $model_order =& m('order');
        $order_info = $model_order->get(array(
            'conditions'    => $order_id,
            'join'          => 'has_orderextm',
            'include'       => array(
                'has_ordergoods',   //取出订单商品
            ),
        ));

        if (!$order_info)
        {
            $this->show_warning('no_such_order');
            return;
        }
        $order_type =& ot('normal');
        $order_detail = $order_type->get_order_detail($order_id, $order_info);
        $order_info['group_id'] = 0;
        if ($order_info['extension'] == 'groupbuy')
        {
            $groupbuy_mod =& m('groupbuy');
            $groupbuy = $groupbuy_mod->get(array(
                'fields' => 'groupbuy.group_id',
                'join' => 'be_join',
                'conditions' => "order_id = {$order_info['order_id']} ",
                )
            );
            $order_info['group_id'] = $groupbuy['group_id'];
        }
        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            if (substr($goods['goods_image'], 0, 7) != 'http://')
            {
                $order_detail['data']['goods_list'][$key]['goods_image'] = WEB_PHOTO_SRC . '/' . $goods['goods_image'];
            }
        }
        //判断订单为心愿单订单
        if($order_info['type'] == 'wishOrder'){
            $wishInfo = &m("wish")->get(array('conditions'=>"order_id = ".$order_id));
            if(empty($wishInfo)){
                $this->show_warning('心愿单信息错误');
                return;
            }
            $wishpayLog = &m('wish_pay_log');
            $wishlog = &m('wish_log');
            //首款
            $firstPrice = $wishpayLog->getPayLog($wishInfo['id'],1);
            //尾款
            $endPrice = $wishpayLog->getPayLog($wishInfo['id'],2);
            //帮砍人数
            $count = $wishlog->getCounts($wishInfo['id']);
            //帮砍金额
            $helpPrice = $wishlog->getInvalid($wishInfo['id']);

            $order_info['wishInfo'] = array(
                'firstPrice' => $firstPrice,
                'endPrice'   => $endPrice,
                'count'      => $count,
                'helpPrice'  => $helpPrice
            );
        }

        $this->assign('order', $order_info);
        $this->assign($order_detail['data']);
        $this->display('order.view.html');
    }

    function test(){
        $order = &m("order");
        $order->writeLog('测试');
    }
    /**
     * 客服介入
    */
    function customer(){
        $postData = $_POST;
        $order = &m('order');
        $member = &m('member');
        $refund = &m('refund');
        $order_id = $postData['order_id'];
        $code = -1;
        $msg = '缺少参数';
        try{
            if($order_id){
                $orderInfo = $order->get(array('conditions'=>"order_id = ".$order_id));
                $msg = '订单信息为空';
                if(!empty($orderInfo)){
//                    $msg = '订单状态已完成或者已取消，不可进行退款';
//                    if($orderInfo['status'] != 0 && $orderInfo['status'] != 40){

                        $msg = '您已经申请了退款！不允许重复申请！';
                        $refundInfo = $refund->get(array("conditions"=>'order_id = '.$order_id));
                        if(empty($refundInfo)){
                            $msg = '当前支付方式不允许退款';
                            if ($orderInfo['payment_code'] != 'cod' && $orderInfo['payment_code'] != 'bank' && $orderInfo['payment_code'] != 'post') {
                                //参数拼接  推送到OMS
                                $refund_sn = $this->gen_refund_sn();
                                $refund_array = array(
                                    'OrderNo' => $orderInfo['order_sn'],
                                    'Note' => $postData['refund_reason'],
                                    'CopName' => '',
                                    'TrackingNo' => '',
                                    'Action' => 1,
                                    'RefundsBillNo' => $refund_sn,
                                    'OverSellNum' => $postData['OverSellNum']
                                );

                                $send_array = array(
                                    'ClientGuid' => CLIENT_GUID,
                                    'ClientName' => CLIENT_NAME,
                                    'CustomerRefundsInfo' => $refund_array
                                );
                                $member->writeLog('发送OMS取消订单接口，报文',json_encode($send_array));
                                $url = API_URL . '/api/order/CustomerRefunds';
                                $rs = $this->sync_data($url, $send_array);
                                $member->writeLog('发送OMS取消订单接口，结果',json_encode($rs));
                                if (!$rs || $rs['code'] != '200') {
                                    $msg = '请求OMS失败';
                                } else {
                                    if ($rs['success'] != true) {
                                        $msg = $rs['msg'];
                                    } else {
                                        //请求oms返回成功后进行ecmall系统取消订单操作
                                        $result = $this->refundOrderPost($orderInfo,$postData,$refund_sn);
                                        $code = $result['code'];
                                        $msg = $result['msg'];
                                    }
                                }
                            }
//                        }
                    }
                }
            }
        }catch(\Exception $e){
            $code = 404;
            $msg = '网络错误';
        }
        $arr['code'] = $code;
        $arr['msg'] = $msg;
        echo json_encode($arr);
        exit();
    }

    function gen_refund_sn() {

        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('Y', $timestamp);
        $z = date('z', $timestamp);
        $refund_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $refund =&m('refund')->get(array('conditions' => 'refund_sn=' . $refund_sn, 'fields' => 'refund_id'));
        if (!$refund) {

            return $refund_sn;
        }
        return $this->gen_refund_sn();
    }

    /*
    * 获取当前订单的未优惠的商品总价
    */

    function _get_total_amount($order_id)
    {
        $total_amount = 0;
        $ordergoods_list = &m('ordergoods')->find(array('conditions'=>'order_id=' . $order_id));
        foreach ($ordergoods_list as $ordergoods) {
            $total_amount += $ordergoods['price'] * $ordergoods['quantity'];
        }
        return $total_amount;
    }

    //生成退款订单
    function refundOrderPost($orderInfo,$postData,$refund_sn){
        $ordergoods_mod = &m('ordergoods');
        $_refund_mod = &m('refund');
        $_order_extm_mod = &m('orderextm');
        //获取单个商品规格
        $goods = $ordergoods_mod->get(array('conditions'=>'order_id=' . $orderInfo['order_id']));
        $code = -1;
        $msg = '订单商品不存在';
        if (!empty($goods)) {
            $msg = '已经申请了退款';
            if(!$_refund_mod
                ->get(array('conditions'=>'order_id=' . $orderInfo['order_id'] . ' AND goods_id=' . $goods['goods_id'] . ' AND spec_id=' . $goods['spec_id']))){
                $msg = '订单记录不存在';
                $order_extm = $_order_extm_mod->get(array('conditions'=>'order_id=' . $orderInfo['order_id']));
                if (!empty($order_extm)) {

                    //优惠后的价格
                    $goods_amount_after_adjust = $orderInfo['goods_amount'];
                    //未优惠的价格
                    $goods_amount_before_adjust = $this->_get_total_amount($orderInfo['order_id']);
                    if ($goods_amount_before_adjust > 0) {
                        $goods_share_rate = round($goods['price'] * $goods['quantity'] / $goods_amount_before_adjust, 2);
                    } else {
                        $goods_share_rate = 0;
                    }
                    if ($goods_amount_before_adjust == $goods_amount_after_adjust) {
                        //最多申请退的商品费用
                        $goods['goods_fee'] = round($goods['price'] * $goods['quantity'] - $orderInfo['discount'] * $goods_share_rate, 2);
                    } elseif ($goods_amount_before_adjust != 0) {
                        $goods_total_fee = $goods['price'] * (1 - ($goods_amount_before_adjust - $goods_amount_after_adjust) / $goods_amount_before_adjust) * $goods['quantity'];
                        //最多申请退的商品费用
                        $goods['goods_fee'] = round($goods_total_fee, 2);
                    } else {
                        //最多申请退的商品费用
                        $goods['goods_fee'] = 0;
                    }
                    $ordergoods = $ordergoods_mod->find(array('conditions'=>'order_id=' . $orderInfo['order_id']));
                    if ($goods_amount_before_adjust > 0) {
                        //最多申请退的运费
                        $goods['shipping_fee'] = round($order_extm['shipping_fee'] * $goods_share_rate, 2);
                    } else {
                        //最多申请退的运费
                        $goods['shipping_fee'] = round($order_extm['shipping_fee'] / count($ordergoods), 2); // 平均分
                    }
                    //由此区分  以上共用  预留方法，暂时不用
//                    $this->_check_post_data($goods);

//                    $refund_shipping_fee = I('post.refund_shipping_fee', 0);


                    $refund_shipped = $postData['refund_shipped'];
                    $refund_data = array(
                        'refund_sn' => $refund_sn,
                        'order_id' => $orderInfo['order_id'],
                        'goods_id' => $goods['goods_id'],
                        'spec_id' => $goods['spec_id'],
                        'refund_reason' => $postData['refund_reason'],
                        'refund_desc' => $postData['refund_desc'],
                        'total_fee' => $goods['goods_fee'] + $goods['shipping_fee'],
                        'goods_fee' => $goods['goods_fee'],
                        'shipping_fee' => $goods['shipping_fee'],
                        'refund_goods_fee' => $goods['goods_fee'],
                        'refund_shipping_fee' => $refund_shipping_fee?$refund_shipping_fee:0,
                        'refund_shipped' => $refund_shipped,
                        'buyer_id' => $orderInfo['buyer_id'],
                        'seller_id' => $orderInfo['seller_id'],
                        'status' => 'WAIT_WAREHOUSE_CONFIRM', // 买家已经申请退款，等待卖家同意
                        'created' => time(),
                        'ask_customer'=>1,
                        'admin_id' => 1
                    );

                    $refund_id = $_refund_mod->add($refund_data);

                    if ($refund_id){
                        $info = &m('refund_message')->add(array(
                            'owner_id' => $orderInfo['buyer_id'],
                            'owner_role' => 'buyer',
                            'refund_id' => $refund_id,
                            'content' => sprintf('买家申请了退款，退款金额为：%s元，退运费金额：%s元，收货情况为：%s，退款原因为：%s，退款说明为：%s', $goods['goods_fee'], $refund_shipping_fee, $refund_shipped, $postData['refund_reason'], $postData['refund_desc']),
                            'created' => time(),
                        ));
                        $logData  = array(
                            'order_id' => $orderInfo['order_id'],
                            'operator' => $orderInfo['buyer_name'],
                            'order_status' => '客户退款',
                            'changed_status' => '退款申请',
                            'order_log_status'=>0,
                            'remark' => '客服申请退款',
                            'log_time' => time(),
                            'operator_type' => 'buyer',
                        );
                        //判断是否为超卖订单  是超卖订单需要给返代金券 0代表没有超卖
                        if($postData['OverSellNum'] > 0){
                            $saveOrderData['OverSellNum'] = $postData['OverSellNum'];
                            $saveOrderOverSellNum = &m("order")->edit($orderInfo['order_id'],$saveOrderData);
                        }
                        $logInfo = &m('orderlog')->add($logData);
                        $code = 1;
                        $msg = '申请成功';
                    } else {
                        $msg = '申请失败';
                    }
                }
            }
        }
        $arr['code'] = $code;
        $arr['msg'] = $msg;
        return $arr;
    }

    /**curl OMS请求**/
    function sync_data($url, $data_string)
    {
        $data_string = json_encode($data_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        $res = curl_exec($ch);
        if (!$res) {
            return false;
        } else {
            return json_decode($res,true);
        }
        return array('code' => $return_code, 'result' => $return_content);
    }
}
?>
